import { ModalHelper } from '@/utils/modal.helper'
import { isFunction } from 'lodash-es'

interface HookOptions<T> {
  /**
   * 确认框标题
   */
  title: string | ((data: T) => string)
  /**
   * 确认框内容
   */
  content: string | ((data: T) => string)
  /**
   * 立即执行条件，可以是boolean或者是返回boolean的一个函数。为true则立即执行(没有确认操作)，为false则会弹出确认框，确认后走相关逻辑函数。不传默认false
   */
  immediate?: ((data: T, ...args: any[]) => boolean) | boolean
  okText?: string
  cancelText?: string
  width?: number
  closable?: boolean
}

export function useConfirm<T = any>(
  options: HookOptions<T>,
  fn: (data: T, ...args: any[]) => Promise<void>,
) {
  function handler(data: T, ...args: any[]): Promise<boolean> {
    return new Promise((resolve) => {
      if (
        (typeof options.immediate === 'boolean' && options.immediate)
        || (typeof options.immediate === 'function'
          && options.immediate(data, ...args))
      ) {
        fn(data, ...args).then(() => resolve(true))
        return
      }
      ModalHelper.error(
        {
          title: isFunction(options.title)
            ? options.title?.(data)
            : options.title,
          content: isFunction(options.content)
            ? options.content?.(data)
            : options.content,
          maskClosable: false,
          okText: options?.okText,
          cancelText: options?.cancelText,
          width: options?.width,
          closable: options?.closable,
          onCancel: () => {
            resolve(false)
          },
        },
        async () => {
          await fn(data, ...args)
          resolve(true)
        },
      )
    })
  }
  return handler
}
